/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package player;

import java.sql.*;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import javax.ejb.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

/**
 *
 * @author denaas
 */
public class PlayerBean {

    private Player player;
    private DataSource dataSource;

    // <editor-fold defaultstate="collapsed" desc="Properties">
    /**
     * @return the dataSource
     */
    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    protected DataSource getDataSource() {
        return dataSource;
    }

    protected void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //</editor-fold>
    private EntityContext context;

    protected EntityContext getContext() {
        return context;
    }

    // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click the + sign on the left to edit the code.">
    // TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise beans, Web services)
    // TODO Add business methods
    // TODO Add create methods
    /**
     * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
     */
    public void setEntityContext(EntityContext aContext) {
        try {
            context = aContext;
            InitialContext ic = new InitialContext();
            Object objRef = ic.lookup("jdbc/den");
            setDataSource((DataSource) PortableRemoteObject.narrow(objRef, DataSource.class));
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @see javax.ejb.EntityBean#ejbActivate()
     */
    public void ejbActivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbPassivate()
     */
    public void ejbPassivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbRemove()
     */
    public void ejbRemove() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("DELETE FROM players WHERE id = ?");
            stmt.setInt(1, getPlayer().getId().intValue());

            if (stmt.executeUpdate() < 1) {
                throw new NoSuchEntityException();
            }



        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    /**
     * @see javax.ejb.EntityBean#unsetEntityContext()
     */
    public void unsetEntityContext() {
        context = null;
    }

    /**
     * @see javax.ejb.EntityBean#ejbLoad()
     */
    public void ejbLoad() {
        Object key = getContext().getPrimaryKey();
        if (key instanceof String) {
            getPlayer().setId(new Integer((String) key));
        } else if (key instanceof Integer) {
            getPlayer().setId((Integer) key);
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("Select * from players where id = ?");
            stmt.setInt(1, getPlayer().getId().intValue());
            res = stmt.executeQuery();
            if (!res.next()) {
                throw new NoSuchEntityException();
            }
            getPlayer().setCountry(res.getString("country"));
            getPlayer().setDateOfBirth(new Integer(res.getInt("dateofbirth")));
            getPlayer().setFirstName(res.getString("firstname"));
            getPlayer().setHeight(new Double(res.getDouble("height")));
            getPlayer().setLastName(res.getString("lastname"));
            getPlayer().setTeamId(new Integer(res.getInt("teamid")));
            getPlayer().setWeight(new Double(res.getDouble("weight")));


        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    /**
     * @see javax.ejb.EntityBean#ejbStore()
     */
    public void ejbStore() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("update players set country=?, dateofbirth=?, firstname=?, height=?,lastname=?, teamid=?, weight=? where id = ?");
            stmt.setString(1, getPlayer().getCountry());
            stmt.setInt(2, getPlayer().getDateOfBirth().intValue());
            stmt.setString(3, getPlayer().getFirstName());
            stmt.setDouble(4, getPlayer().getHeight().doubleValue());
            stmt.setString(5, getPlayer().getLastName());
            stmt.setInt(6, getPlayer().getTeamId().intValue());
            stmt.setDouble(7, getPlayer().getWeight().doubleValue());
            stmt.setInt(8, getPlayer().getId().intValue());

            if (stmt.executeUpdate() < 1) {
                throw new NoSuchEntityException();
            }



        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    // </editor-fold>
    /**
     * See EJB 2.0 and EJB 2.1 section 12.2.5
     */
    public Integer ejbCreate(Player pl) throws CreateException {
        setPlayer(pl);

        Connection conn = null;
        PreparedStatement stmt = null;
        PreparedStatement stmt2 = null;
        ResultSet res2 = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("INSERT INTO players (country, dateofbirth, firstname, height, lastname, teamid, weight, id)"
                    + "VALUES (?,?,?,?,?,?,?,SEQPLAYER.NEXTVAL)");
            stmt.setString(1, getPlayer().getCountry());
            stmt.setInt(2, getPlayer().getDateOfBirth().intValue());
            stmt.setString(3, getPlayer().getFirstName());
            stmt.setDouble(4, getPlayer().getHeight().doubleValue());
            stmt.setString(5, getPlayer().getLastName());
            stmt.setInt(6, getPlayer().getTeamId().intValue());
            stmt.setDouble(7, getPlayer().getWeight().doubleValue());

            if (stmt.executeUpdate() != 1) {
                throw new CreateException();
            }

            stmt2 = conn.prepareStatement("select seqplayer.currval from players");
            res2 = stmt2.executeQuery();
            res2.next();
            getPlayer().setId(new Integer(res2.getInt(1)));


            return getPlayer().getId();

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                stmt2.close();
                res2.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public void ejbPostCreate(Player pl) throws CreateException {
    }

    public java.lang.Integer ejbFindByPrimaryKey(java.lang.Integer aKey) throws ObjectNotFoundException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from players where id=?");
            stmt.setInt(1, aKey.intValue());
            res = stmt.executeQuery();

            if (!res.next()) {
                throw new ObjectNotFoundException();
            }


            return aKey;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public Collection ejbFindByName(String aName) throws FinderException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from players where lastname=?");
            stmt.setString(1, aName);
            res = stmt.executeQuery();

            Vector keys = new Vector();

            while (res.next()) {
                String empno = res.getString(1);
                keys.addElement(empno);
            }


            return keys;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }

    public Collection ejbFindAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from players");
            res = stmt.executeQuery();
            Vector keys = new Vector();

            while (res.next()) {
                String empno = res.getString(1);
                keys.addElement(empno);
            }


            return keys;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }
    
    public Collection ejbFindByTeam(Integer teamId) throws FinderException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = getDataSource().getConnection();
            stmt = conn.prepareStatement("select id from players where teamid=?");
            stmt.setInt(1,teamId.intValue());
            res = stmt.executeQuery();

            Vector keys = new Vector();

            while (res.next()) {
                String empno = res.getString(1);
                keys.addElement(empno);
            }

            return keys;

        } catch (SQLException e) {
            throw new EJBException();
        } finally {
            try {
                stmt.close();
                res.close();
                conn.close();
            } catch (SQLException ex) {
                throw new EJBException();
            }
        }
    }
}
